package com.kiki.oauth.utils;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.kiki.oauth.bean.UserInfo;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;

import java.util.*;

public class UserInfoUtil {

    public static Long getUserId(){
        Object userInfo = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if(userInfo instanceof Map){
            Object userid = ((Map)userInfo).get("userid");
            return userid==null?null:Long.valueOf(userid.toString());
        }else if(userInfo instanceof UserInfo){
            return ((UserInfo)userInfo).getUserid();
        }else{
            return null;
        }
    }

    public static String getUsername(){
        Object userInfo = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if(userInfo instanceof Map){
            return (String)((Map)userInfo).get("user_name");
        }else if(userInfo instanceof UserInfo){
            return ((UserInfo)userInfo).getUsername();
        }else if(userInfo instanceof String){
            return (String)userInfo;
        }else{
            return null;
        }
    }

    public static Set<String> getUserAuthorities(){
        Set<String> authoritiesSet = new HashSet<String>();
        Collection<? extends GrantedAuthority> authorities = SecurityContextHolder.getContext().getAuthentication().getAuthorities();
        if(CollUtil.isEmpty(authorities)){
            return authoritiesSet;
        }
        Iterator<? extends GrantedAuthority> iterator = authorities.iterator();
        while (iterator.hasNext()){
            authoritiesSet.add(iterator.next().getAuthority());
        }
        return authoritiesSet;
    }
}
